// pages/truckCenter/add.js

import requestUtil from '../../baseRequest.js'
import requestUrls from '../../requestUrl.js'
import {$Message} from '../../components/base/index'
import commonUtils from '../../utils/util.js'
import imageUtils from '../../utils/imageUtils.js'
let openid = wx.getStorageSync('openid')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    driverInfo: {},
    orderCenterId: '',
    openid: openid,
    //是否提交过
    isSubmit: false,
    fromRegion: [],
    toRegion: [],
    truckType: '',
    endDate: '',
    //驾驶证图片路径
    driverLisenceImageUrl: '',
    //行驶证图片路径
    drivingLisenceImageUrl: '',
    //驾驶证
    mainDriverLicense: [],
    //行驶证
    vehicleLicense: [],
    ifPlateNumber:false,
  },
  submitForm: function (event) {
    const {
      target: {
        dataset
      },
      value
    } = event.detail;
    const {
      submittype = ''
    } = dataset || {};
    //校验填入数据
    if (this.checkFormData(value, submittype)) {
      if (this.data.isSubmit) {
        this.saveTruckCenter();
      } else {
        this.setData({
          showSpin: true,
          isUploadDriverLisence: true,
          formDataTemp: {
            openId: this.data.openid,
            criteria: {
              orderCenterId: this.data.orderCenterId,
              truckCenter: {
                mainDriverName: value.name,
                mainDriverPhone: value.mobile,
                plateNumber: value.carNumber,
                truckTypeName: this.data.truckType,
                fromProvinceId: this.data.fromProvinceId,
                fromCityId: this.data.fromCityId,
                fromCountyId: this.data.fromCountyId,
                fromProvinceName: this.data.fromProvinceName,
                fromCityName: this.data.fromCityName,
                fromCountyName: this.data.fromCountyName,
                toProvinceId: this.data.toProvinceId,
                toCityId: this.data.toCityId,
                toCountyId: this.data.toCountyId,
                toProvinceName: this.data.toProvinceName,
                toCityName: this.data.toCityName,
                toCountyName: this.data.toCountyName,
                freeBeginTime: this.data.beginDate,
                freeEndTime: this.data.endDate,
                maxVolume: value.leftVolume,
                maxWeight: value.leftWeight,
              }
            }
          }
        })
      }


      //封装传输对象
      // const formData = {
      //   openId: this.data.openid,
      //   criteria: {
      //     orderCenterId: this.data.orderCenterId,
      //     truckCenter: {
      //       mainDriverName: value.name,
      //       mainDriverPhone: value.mobile,
      //       plateNumber: value.carNumber,
      //       truckTypeName: this.data.truckType,
      //       fromProvinceId: this.data.fromProvinceId,
      //       fromCityId: this.data.fromCityId,
      //       fromCountyId: this.data.fromCountyId,
      //       fromProvinceName: this.data.fromProvinceName,
      //       fromCityName: this.data.fromCityName,
      //       fromCountyName: this.data.fromCountyName,
      //       toProvinceId: this.data.toProvinceId,
      //       toCityId: this.data.toCityId,
      //       toCountyId: this.data.toCountyId,
      //       toProvinceName: this.data.toProvinceName,
      //       toCityName: this.data.toCityName,
      //       toCountyName: this.data.toCountyName,
      //       freeBeginTime: this.data.beginDate,
      //       freeEndTime: this.data.endDate,
      //       maxVolume:value.leftVolume,
      //       maxWeight:value.leftWeight,
      //       orderTruckImageList,
      //     }
      //   }
      // };

      // requestUtil.postRequest(requestUrls.truckCenter.saveTruckCenter, formData, (res) => {
      //   if (!res.hasError) {
      //     wx.showModal({
      //       title: '温馨提示',
      //       content: '操作成功',
      //       showCancel: false,
      //       success: res => {
      //         wx.switchTab({
      //           url:'/pages/homev2/index'
      //         })
      //       }
      //   })
      //   }
      // })
    };

  },
  publishTruck(event){
    const { value } = event.detail;
    console.log(this.data);
    const formData = {
      openId: this.data.openid,
      criteria:{
        orderCenterId: this.data.orderCenterId || this.data.truckCenter.orderCenterId,
        truckCenter:{
          plateNumber:this.data.truckCenter.plateNumber,
          mainDriverName: value.mainDriverName,
          mainDriverPhone: value.mainDriverPhone,
          ...this.data.truckInfo,
          ...this.data.typeLength,
          orderTruckImageList:[
            {orderTypeId: 'TRUCK_CENTER', imageTypeId: 'LICENSE_IMAGE',imageUrl:this.data.mainDriverLicense[0].imageUrl},
            {orderTypeId: 'TRUCK_CENTER', imageTypeId: 'VEHICLE_LICENSE',imageUrl:this.data.vehicleLicense[0].imageUrl},
          ]
        }
      }
    };
    this.setData({showLoading:true});
    if(this.checkPublishTruck(value)){
      requestUtil.postRequest(requestUrls.truckCenter.saveTruckCenter, { ...formData }, (res) => {
        this.setData({showLoading:false});
        if (!res.hasError) {
          wx.removeStorageSync('truckCenter');
          wx.showModal({
            title: '温馨提示',
            content: '操作成功',
            showCancel: false,
            success: res => {
              wx.switchTab({
                url: '/pages/homev2/index'
              })
            }
          })
        }
      })
    }
    this.setData({showLoading:false});
  },
  checkPublishTruck(formData){
    if(!this.data.orderCenterId&& !this.data.truckCenter.orderCenterId){
      this.showErrorMessage('申请的货物信息不能为空');
      return false;
    }
    if (formData.mainDriverName === '') {
      this.showErrorMessage('姓名不能为空');
      return false;
    }
    if (commonUtils.isEmoji(formData.mainDriverName)) {
      this.showErrorMessage('姓名不符合要求');
      return false;
    }
    const {truckCenter} = this.data;
    console.log({truckCenter});
    if (!truckCenter.plateNumber || truckCenter.plateNumber.length != 7) {
      this.showErrorMessage('请按要求填写认证车牌号码')
      return false
    }
    if(formData.mainDriverPhone===''){
      this.showErrorMessage('联系方式不能为空');
      return false;
    }
    if(!commonUtils.checkTelphoneNumber(formData.mainDriverPhone)){
      this.showErrorMessage('联系方式不符合要求');
      return false;
    }
    return true;
  },
  getTypeLength(){
    wx.setStorageSync('truckCenter', this.data.truckCenter);
    wx.navigateTo({
      url: '/pages/truckCenter/typeLength?orderType=truckCenter&fromPage=add',
    })
  },
  getTruckInfo(){
    wx.setStorageSync('truckCenter', this.data.truckCenter);
    wx.navigateTo({
      url: '/pages/truckCenter/truckInfo?fromPage=add',
    })
  },
  removeJSZ(){
    this.setData({
      mainDriverLicense:[],
    })
  },
  removeXSZ(){
    this.setData({
      vehicleLicense:[],
    })
  },
  showPlateNumber(){
    this.setData({
      ifPlateNumber:true,
    })
  },
  hidePlateNumber(){
    this.setData({
      ifPlateNumber:false,
    })
  },
  changePlateNumber(event){
    const {detail} = event;
    wx.setStorageSync('plateNumber', detail);
    this.setData({
      truckCenter:{
        ...this.data.truckCenter,
        plateNumber:detail,
      }
    })
    this.hidePlateNumber();
  },
  /**初始化获取救援司机信息 */
  getDriverInfo() {
    if (!this.data.openid) {
      this.setData({
        openid: wx.getStorageSync('openid')
      })
    }
    let param = {
      'openid': this.data.openid
    }
    requestUtil.postRequest(requestUrls.transportConfirm.init, param, (res) => {
      const mainDriverLicense = wx.getStorageSync('mainDriverLicense');
      const vehicleLicense = wx.getStorageSync('vehicleLicense');
      const plateNumber = wx.getStorageSync('plateNumber');
      this.setData({
        truckCenter:{
          ...this.data.truckCenter,
          mainDriverName:res.name,
          mainDriverPhone:res.mobile,
          plateNumber:plateNumber,
          mainDriverLicenseUrl:mainDriverLicense[0].imageUrl,
          vehicleLicenseUrl:vehicleLicense[0].imageUrl,
        },
        driverInfo:res,
        mainDriverLicense,
        vehicleLicense
      })
    })
  },
  /**显示错误信息 */
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  checkFormData: function (formData, submitType) {
    if (submitType === 'apply') {
      //校验出发地，目的地，车型，开始时间，截止时间
      if (this.data.fromProvinceId === '' || this.data.fromCityId === '' || this.fromCountyId === '') {
        this.showErrorMessage('出发地信息不能为空');
        return false;
      }
      if (this.data.toProvinceId === '' || this.data.toCityId === '' || this.data.toCountyId === '') {
        this.showErrorMessage('目的地信息不能为空');
        return false;
      }
      if (this.data.truckType === '') {
        this.showErrorMessage('车辆类型不能为空');
        return false;
      }
      if (this.data.beginDate === '') {
        this.showErrorMessage('起始时间不能为空');
        return false;
      }
      // if (this.data.beginDate < this.data.startChoiceDate) {
      //   this.showErrorMessage('起始时间已过期');
      //   return false;
      // }
      if (this.data.endDate === '') {
        this.showErrorMessage('截止时间不能为空');
        return false;
      }
      if (this.data.endDate < this.data.startChoiceDate || this.data.endDate < this.data.beginDate) {
        this.showErrorMessage('截止时间已过期或在起始时间之前');
        return false;
      }
    }
    if (formData.name === '') {
      this.showErrorMessage('姓名不能为空');
      return false;
    }
    if (commonUtils.isEmoji(formData.name)) {
      this.showErrorMessage('姓名不符合要求');
      return false;
    }
    if (formData.leftVolume === '') {
      this.showErrorMessage('剩余空间不能为空');
      return false;
    }
    if (Number(formData.leftVolume) <= 0 || !commonUtils.checkDouble(formData.leftVolume)) {
      this.showErrorMessage('剩余空间不符合要求');
      return false;
    }
    if (formData.leftWeight === '') {
      this.showErrorMessage('剩余载重不能为空');
      return false;
    }
    if (Number(formData.leftWeight) <= 0 || !commonUtils.checkDouble(formData.leftWeight)) {
      this.showErrorMessage('剩余载重不符合要求');
      return false;
    }
    if (!formData.carNumber || formData.carNumber.length != 7) {
      this.showErrorMessage('请按要求填写认证车牌号码')
      return false
    }
    if (!formData.drivingLicense || formData.drivingLicense.length != 1) {
      this.showErrorMessage('驾驶证上传图片数量有误')
      return false
    }
    return true;
  },

  //修改车辆类型
  bindTruckTypeChange: function (event) {
    const truckTypeValue = event.detail.value;
    this.setData({
      truckType: this.data.truckTypeList[truckTypeValue]
    })
  },
  //修改起始时间
  bindBeginDateChange: function (event) {
    this.setData({
      beginDate: event.detail.value
    })
  },
  //修改截止时间
  bindEndDateChange: function (event) {
    this.setData({
      endDate: event.detail.value
    })
  },
  afterJSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl +requestUrls.uploadUrl.driverLisence;
    let filePath = file.path;
    let imgList = [];
    imageUtils.uploadImage(uploadUrl,filePath,(url)=>{
      imgList.push({ url: requestUrls.baseImagePrefixUrl+url,imageUrl: url});
      this.setData({
        mainDriverLicense: imgList,
      });
      wx.setStorageSync('mainDriverLicense', imgList);
    });
  },
  afterXSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl +requestUrls.uploadUrl.drivingLisence;
    let filePath = file.path;
    let imgList = [];
    imageUtils.uploadImage(uploadUrl,filePath,(url)=>{
      imgList.push({ url: requestUrls.baseImagePrefixUrl+url,imageUrl: url })
        this.setData({
          vehicleLicense: imgList,
        });
        wx.setStorageSync('vehicleLicense', imgList);
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {orderCenterId} = options;
    let optName = '发布';
    if(orderCenterId){
      optName = '提交';
      this.setData({
        orderCenterId: orderCenterId || '',
        truckCenter:{
          ...this.data.truckCenter,
          orderCenterId,
        },
        optName,
      })
    }
    this.getDriverInfo();
    const truckInfo = wx.getStorageSync('truckInfo');
    const typeLength = wx.getStorageSync('typeLength');
    const truckCenter = wx.getStorageSync('truckCenter');
    const mainDriverLicense = wx.getStorageSync('mainDriverLicense');
    const vehicleLicense = wx.getStorageSync('vehicleLicense');
    console.log(truckInfo);
    this.setData({
      truckInfo,
      typeLength,
      mainDriverLicense,
      vehicleLicense,
    })
    if(truckCenter){
      if(truckCenter.orderCenterId){
        optName = '提交';
      }
      this.setData({
        truckCenter,
        optName,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: '/pages/homev2/index'
    }
  }
})